package com.yuntoyun.fwcore.security.md5sign;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

/**
 * Md5签名工具类
 */
public class Md5Sign {

    /**
     * 加签后的密文
     *
     * @param hashmap
     * @param md5_key
     * @return
     */
    public static String addSign(Map<String, String> hashmap, @NonNull String md5_key) {
        if (hashmap == null) {
            return "";
        }
        return addSignMD5(hashmap, md5_key);
    }

    /**
     * 验证签名合法性
     *
     * @param hashmap
     * @param md5_key
     * @return
     */
    public static boolean checkSign(Map<String, String> hashmap, @NonNull String signStr,
                                    @NonNull String md5_key) {
        if (hashmap == null || TextUtils.isEmpty(signStr)) {
            return false;
        }

        // 生成待签名串
        String sign_src = genSignData(hashmap);
        sign_src += "&key=" + md5_key;
        try {
            if (signStr.equals(Md5Algorithm.getInstance().md5Digest(
                    sign_src.getBytes("utf-8")))) {
                return true;
            } else {
                return false;
            }
        } catch (UnsupportedEncodingException e) {
            return false;
        }
    }

    /**
     * 转换Md5字符串
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        try {
            return Md5Algorithm.getInstance().md5Digest(
                    str.getBytes("utf-8"));
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 检测 null, "null", 空字符
     *
     * @param str
     * @return
     */
    private static boolean isnull(String str) {
        if (null == str || str.equalsIgnoreCase("null") || str.equals("")) {
            return true;
        } else
            return false;
    }

    /**
     * 拼装待签名的数据
     *
     * @param hashmap
     * @return
     */
    private static String genSignData(Map<String, String> hashmap) {
        StringBuffer content = new StringBuffer();

        // 按照key做首字母升序排列
        List<String> keys = new ArrayList<String>(hashmap.keySet());
        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            if ("sign".equals(key)) {
                continue;
            }
            String value = hashmap.get(key);
            // 空字符串不参与签名
            if (isnull(value)) {
                continue;
            }
            content.append((i == 0 ? "" : "&") + key + "=" + value);
        }
        String signSrc = content.toString();
        if (signSrc.startsWith("&")) {
            signSrc = signSrc.replaceFirst("&", "");
        }
        return signSrc;
    }

    /**
     * 对数据进行签名
     *
     * @param hashmap
     * @param md5_key
     * @return
     */
    private static String addSignMD5(Map<String, String> hashmap, @NonNull String md5_key) {
        if (hashmap == null) {
            return "";
        }
        // 生成待签名串
        String sign_src = genSignData(hashmap);
        sign_src += "&key=" + md5_key;
        try {
            return Md5Algorithm.getInstance().md5Digest(
                    sign_src.getBytes("utf-8"));
        } catch (Exception e) {
            return "";
        }
    }
}
